package com.isoftstone.disk.spring.security;

import com.isoftstone.disk.login.entity.DiskUserEntity;
import com.isoftstone.disk.login.entity.PtUserEntity;
import com.isoftstone.disk.login.service.LoginService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class GdmtUserDetailsService implements UserDetailsService {
    private Logger logger = LogManager.getLogger(this.getClass());
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private LoginService loginService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        List<PtUserEntity> list = loginService.queryUserInfoByUserName(username);
        if(list.size() == 0){
            throw new IllegalArgumentException(username + " user is not exit.");
        }
        logger.info(list.get(0).getUserUuid());


        List<GrantedAuthority> collection = new ArrayList<>();
        List<String> authoList = loginService.queryUserAuthByUserId(list.get(0).getUserUuid());
        for(String autho : authoList){
            collection.add(new SimpleGrantedAuthority("ROLE_" + autho));
        }
        // 参数分别是：用户名，密码，用户权限
        DiskUserEntity diskUserEntity = new DiskUserEntity(username, list.get(0).getPassword(), collection);
        diskUserEntity.setEmail(list.get(0).getEmail());
        diskUserEntity.setMobile(list.get(0).getMobile());
        diskUserEntity.setNiceName(list.get(0).getNiceName());
        diskUserEntity.setUserUuid(list.get(0).getUserUuid());
        return diskUserEntity;
    }

}
